package cn.invengo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // auth init users and roles
        auth.inMemoryAuthentication().withUser("admin").password("123").roles("ADMIN").and()
                .withUser("sys").password("123").roles("SYSTEM").and()
                .withUser("test").password("123").roles("TEST").and()
                .withUser("guest").password("123").roles("GUEST");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .formLogin().defaultSuccessUrl("/index").loginPage("/login").failureUrl("/login?error").permitAll()
                .usernameParameter("username").passwordParameter("password").and()
                .logout().logoutSuccessUrl("/login?logout").permitAll().and()
                .authorizeRequests().antMatchers("/static/**").permitAll()
                .anyRequest().authenticated().and()
               .sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());
    }

    // see http://stackoverflow.com/questions/11271449/how-can-i-have-list-of-all-users-logged-in-via-spring-secuirty-my-web-applicat
    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    /*@Bean
    public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
        return new ServletListenerRegistrationBean<HttpSessionEventPublisher>(new HttpSessionEventPublisher());
    }*/

}
